package com.soms.servlet;

import cn.hutool.json.JSONUtil;
import com.soms.constants.LoginConst;
import com.soms.entity.User;
import com.soms.service.UserService;
import com.soms.service.impl.UserServiceImpl;
import com.soms.util.HttpResponseUtil;
import com.soms.util.ResultUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

@WebServlet("/server/user")
@MultipartConfig // 支持上传
public class UserServlet extends HttpServlet {
    private final UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req,
                         HttpServletResponse resp)
            throws ServletException, IOException {
        String type = req.getParameter("type");
        if (type != null) {
            switch (type) {
                case "uploadAvatar":
                    doUploadAvatar(req, resp);
                    break;
                case "getAvatar":
                    doGetAvatar(req, resp);
                    break;
                case "getLoginUser":
                    doGetLoginUser(req, resp);
                    break;
                case "setting":
                    doSetting(req, resp);
                    break;
                case "updatePassword":
                    doUpdatePassword(req, resp);
                    break;
                default:

                    break;
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req,
                          HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req, resp);
    }

    /**
     * 上传头像
     *
     * @param req
     * @param resp
     */
    private void doUploadAvatar(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 先判断是否已经登录
        HttpSession session = req.getSession(false);
        if (session == null || session.getAttribute(LoginConst.USER_CODE) == null) {
            HttpResponseUtil.writeJson(resp, JSONUtil.toJsonStr(ResultUtil.unAuthenticated()));
            return;
        }
        // layui上传图片的默认字段名称
        Part file = req.getPart("file");
        // 判断文件大小
        long size = file.getSize(); // 字节
        size /= 1024; // KB
        if (size > 500) {
            HttpResponseUtil.writeJson(resp, JSONUtil.toJsonStr(ResultUtil.fail("头像不能大于500KB")));
            return;
        }
        // 获取登录用户的用户编码
        String userCode = session.getAttribute(LoginConst.USER_CODE).toString();
        InputStream is = file.getInputStream();
        // base64编码存储图片
        String avatar = Base64.getEncoder().encodeToString(is.readAllBytes());
        // 图片的格式
        String contentType = file.getContentType();
        // 拼接成能够被浏览器解析成图片的base64编码字符串
        avatar = "data:" + contentType + ";base64," + avatar;
        HttpResponseUtil.writeJson(resp, userService.uploadAvatar(userCode, avatar));
        is.close();
    }

    /**
     * 获取当前登录用户的头像
     *
     * @param req
     * @param resp
     */
    private void doGetAvatar(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 先判断是否已经登录
        HttpSession session = req.getSession(false);
        if (session == null || session.getAttribute(LoginConst.USER_CODE) == null) {
            HttpResponseUtil.writeJson(resp, JSONUtil.toJsonStr(ResultUtil.unAuthenticated()));
            return;
        }
        // 获取登录用户的用户编码
        String userCode = session.getAttribute(LoginConst.USER_CODE).toString();
        HttpResponseUtil.writeJson(resp, userService.getAvatar(userCode));
    }

    /**
     * 获取当前登录用户的信息
     *
     * @param req
     * @param resp
     */
    private void doGetLoginUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 先判断是否已经登录
        HttpSession session = req.getSession(false);
        if (session == null || session.getAttribute(LoginConst.USER_CODE) == null) {
            HttpResponseUtil.writeJson(resp, JSONUtil.toJsonStr(ResultUtil.unAuthenticated()));
            return;
        }
        // 获取登录用户的用户编码
        String userCode = session.getAttribute(LoginConst.USER_CODE).toString();
        User loginUser = userService.getUserByUserCode(userCode);
        HttpResponseUtil.writeJson(resp, JSONUtil.toJsonStr(ResultUtil.success(null, loginUser)));
    }

    /**
     * 修改个人资料
     *
     * @param req
     * @param resp
     */
    private void doSetting(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 就是符合User类结构的JSON字符串
        String data = req.getParameter("data");
        // JSON字符串转Java对象
        User user = JSONUtil.toBean(data, User.class);
        HttpResponseUtil.writeJson(resp, userService.updateUserBySelf(user));
    }

    /**
     * 修改当前用户的密码
     *
     * @param req
     * @param resp
     */
    private void doUpdatePassword(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("修改密码");
        // 先判断是否已经登录
        HttpSession session = req.getSession(false);
        if (session == null || session.getAttribute(LoginConst.USER_CODE) == null) {
            HttpResponseUtil.writeJson(resp, JSONUtil.toJsonStr(ResultUtil.unAuthenticated()));
            return;
        }
        // 获取登录用户的用户编码
        String userCode = session.getAttribute(LoginConst.USER_CODE).toString();
        String oldPassword = req.getParameter("oldPassword");
        String newPassword = req.getParameter("newPassword");
        String rePassword = req.getParameter("rePassword");
        HttpResponseUtil.writeJson(resp,
                userService.updatePassword(userCode, oldPassword, newPassword, rePassword));
    }
}
